﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using InfoJetSoft.Service.Entity;
using InfoJetSoft.Service.Util;
using InfoJetSoft.SharePointPeople;

//CID 0749 //2011.08.30 //Begin
namespace InfoJetSoft.Service.Worker
{
    class DigitalSignaturePrepareWorker
    {
        public static string prepareSignature(Form form)
        {
            string ajaxBracket = FormUtil.getAjaxBracket(form);
            
            StringBuilder buffer = new StringBuilder();
            buffer.Append(ajaxBracket);
            string parent = "";
            if (ConfigUtil.UseAJAX())
            {
                parent = "";
            }
            else
            {
                buffer.Append("<script>");
                parent = "parent.";
            }
            buffer.Append(parent + "InfoJet_StopProgress();");
            buffer.Append(parent + "InfoJet_Postbacking = 0;");
            buffer.Append(parent + "InfoJet_OnPostbackEnd();");

            try
            {
                string formId = form.HttpContext.Request.Params["xdoc_param_form_id"];
                string blockName = form.HttpContext.Request.Params["xdoc_param_dsig_block"];

                SignedDataBlock block = null;
                if (form.Manifest.SignedDataBlockList != null)
                {
                    foreach (SignedDataBlock sdBlock in form.Manifest.SignedDataBlockList)
                    {
                        if (sdBlock.Name.Equals(blockName))
                        {
                            block = sdBlock;
                            break;
                        }
                    }
                }
                if (block != null)
                {
                    FormParseRequestParamWorker.parseRequestParam(form);
                    FormBuildXMLDocByFieldListWorker.buildXMLDocByFieldList(form);

                    if (InlineFileUtil.isInlineFileEnabled(form))
                    {
                        XFileAttachmentEncoder.restoreFiles(form);
                        XImageEncoder.restoreImages(form);
                    }

                    JetIdCache idCache = new JetIdCache(form.XmlDoc.DocumentElement);
                    string formXml = form.XmlDoc.OuterXml;
                    idCache.reset();

                    XmlNode dataNode = DOMUtil.selectANode(form.XmlDoc, block.Data, form.XmlNsResolver);
                    XmlNode locationNode = DOMUtil.selectANode(form.XmlDoc, block.Location, form.XmlNsResolver);
                    if (dataNode != null && locationNode != null)
                    {
                        string viewId = (string)form.ParamTable[JetConstant.XDOC_PARAM_VIEW_ID];
                        string viewName = form.Manifest.getView(viewId).Name;

                        DsigData dsigData = new DsigData();
                        dsigData.Name = block.Name;
                        dsigData.Data = block.Data;
                        dsigData.Location = block.Location;
                        dsigData.Mode = block.Mode;
                        dsigData.Message = block.Message;
                        dsigData.Xml = formXml;
                        dsigData.ViewName = viewName;
                        if (form.Manifest.Size > 2000 * 1000)
                        {
                            dsigData.Fingerprint = "";
                        }
                        else
                        {
                            dsigData.Fingerprint = form.Manifest.Digest;
                        }

                        dsigData.CtrlId = "";
                        //CID 1503 //2012.12.22 //Begin
                        string isline = form.HttpContext.Request.Params["xdoc_param_dsig_isline"];
                        if (isline != null && isline == "true")
                        {
                            View view = form.Manifest.getView(viewId);
                            if (view.SignatureLines != null)
                            {
                                foreach (SignatureLine signatureLine in view.SignatureLines)
                                {
                                    if (signatureLine.SignedDataBlock.Equals(block.Name))
                                    {
                                        dsigData.CtrlId = signatureLine.Name;
                                    }
                                }
                            }
                        }
                        //CID 1503 //2012.12.22 //End

                        string jsData = Newtonsoft.Json.JavaScriptConvert.SerializeObject(dsigData);
                        buffer.Append("var InfoJet_CurrentDsigData = ");
                        buffer.Append(jsData);
                        buffer.Append(";");

                        buffer.Append("InfoJet_ToSign(InfoJet_CurrentDsigData);");
                    }
                }
            }
            catch (Exception e)
            {
                //CID 1513 //2012.12.26 //Begin
                string message = ScriptHtmlUtil.formatMessage(e.Message);
                buffer.Append(parent + "alert(\"" + message + "\");");
                //CID 1513 //2012.12.26 //End
            }

            if (!ConfigUtil.UseAJAX())
            {
                buffer.Append("</script>");
            }

            buffer.Append(ajaxBracket);
            return buffer.ToString();
        }

        private static string getNodePath(XmlNode node)
        {
            if (node == null)
            {
                return null;
            }

            StringBuilder path = new StringBuilder();
            XmlElement element = null;
            if (node is XmlAttribute)
            {
                path.Append("attribute::*[namespace-uri()=\"" + node.NamespaceURI + "\" and local-name()=\"" + node.LocalName + "\"]");
                XmlAttribute attr = (XmlAttribute)node;
                element = attr.OwnerElement;
                if (element == null)
                {
                    return null;
                }
            }
            else if (node is XmlElement)
            {
                element = (XmlElement)node;
            }
            else
            {
                return null;
            }

            while (!element.Equals(node.OwnerDocument.DocumentElement))
            {
                if (path.Length > 0)
                {
                    path.Insert(0, "*[namespace-uri()=\"" + element.NamespaceURI + "\" and local-name()=\"" + element.LocalName + "\"]/");
                }
                else
                {
                    path.Insert(0, "*[namespace-uri()=\"" + element.NamespaceURI + "\" and local-name()=\"" + element.LocalName + "\"]");
                }
                element = (XmlElement)element.ParentNode;
            }

            if (path.Length > 0)
            {
                path.Insert(0, "*[namespace-uri()=\"" + element.NamespaceURI + "\" and local-name()=\"" + element.LocalName + "\"]/");
            }
            else
            {
                path.Insert(0, "*[namespace-uri()=\"" + element.NamespaceURI + "\" and local-name()=\"" + element.LocalName + "\"]");
            }

            path.Insert(0, "/");

            return path.ToString();
        }
    }

    class DsigData
    {
        public string Name
        {
            get;
            set;
        }

        public string Data
        {
            get;
            set;
        }

        public string Location
        {
            get;
            set;
        }

        public string Mode
        {
            get;
            set;
        }

        public string Message
        {
            get;
            set;
        }

        public string Xml
        {
            get;
            set;
        }

        public string ViewName
        {
            get;
            set;
        }

        public string Fingerprint
        {
            get;
            set;
        }

        //CID 1503 //2012.12.21 //Begin
        public string CtrlId
        {
            get;
            set;
        }
        //CID 1503 //2012.12.21 //End
    }
}
//CID 0749 //2011.09.20 //End